function createTable(ID,y,m)
{
        jQuery("#gbox_table"+ID).replaceWith($('<div id="pager'+ID+'"></div><table id="table'+ID+'"></table>'));
        var lastsel2=0;
        var lastsel=0;
        var days=(m!=2?((m%2)^(m>7))+30:(!(y%400)||!(y%4)&&(y%25)?29:28))
        var names=['ID',name];
        var cols=[{name:'id',index:'id', width:1,sortable: false, align:"center", hidden:true},
                          {name:'name',index:'name', width:200,sortable: false,editable:false}];
        ;
        for(var i=1;i<=days;i++)

        {

                        names[i+1]=""+i+"<br>"+dayA[new Date(y,m-1,i).getDay()];
                        cols[i+1]={name:'d'+i,index:'d'+i, width:40,editable:true,sortable: false,editrules:{required:false,integer:true}}
                }
        jQuery("#table"+ID).jqGrid({
                url:'/admin/showprice/'+y+'/'+m+'/'+ID,
            editurl:'/admin/editprice/'+y+'/'+m+'/'+ID,
                datatype: "json",
            mtype: 'POST',
                colNames:names,
                colModel:cols,
                pager: '#pager'+ID,
            viewrecords: true,
            caption:ID,
            onSelectRow: function (id) {
                        if (id && id !== lastsel2) {

                                jQuery('#table'+ID).jqGrid('restoreRow', lastsel2);
                                jQuery('#table'+ID).jqGrid('editRow', id, true);
                            lastsel2 = id;
                        }
                    },
            width:"1200",
            height:"100%"
        });
        jQuery("#table"+ID).jqGrid('navGrid','#pager'+ID,{edit:true,add:false,del:false,search:false});
        $("#table"+ID+" .ui-jqgrid-title").replaceWith('888');
        $("#gbox_table"+ID+" span.ui-jqgrid-title").replaceWith("<div class='editPriceTable' idTable="+ID+"><a href='javascript:void(0)' >Редактировать данные</a></div>");
        $(".editPriceTable").contextMenu({ menu: 'myMenu', leftButton: true },
                        function(action, el, pos) { contextMenuWork(action, el, pos); });
}

function addRowlist(where)
{
        var num=parseInt($('#numRows','.mWindowTest').val())+1;
        $('.mWindowTest')
                .find('#numRows')
                .val(num)
                .end()
                .find('#'+where)
                .prepend($('.row','#'+where)
                                .filter(':last-child')
                                .clone()
                                        .find('.addNewRow')
                                        .attr('num',num)
                                .end()
                                        .find('select')
                                        .attr('name',where+'[price]['+num+']')
                                .end()
                                .find('.rowT')
                                .append('<div class="ui-icon ui-icon-trash" width=16 height=16 onClick="removeRowlist(\''+where+'\');"></div>')
                                .end());
}
function removeRowlist(where)
{
        var num=parseInt($('#numRows','.mWindowTest').val())-1;
        $('.mWindowTest')
        .find('#numRows')
        .val(num)
        .end()
        .find('#'+where)
        .find('.row')
        .filter(':first-child')
        .remove();
}
function loadtableoptions(where)
{
	$(where).empty();
	$.ajax({
		url: '/admin/getlisttableoptions/'+$('#service').attr('type'),
		type:'post',
		success:function(data)
		{
			//console.log(data);
			/*switch($('#service').attr('type'))
			{
				case '1':*/
					for(row in data)
					{
						
						if(data[row].constructor!=Object)
						{
							$(where)
							.append(data[row]+': <input type=text name=dop['+data[row]+'] size=3>' +
									'<br />');
						}
						else
						{
							$(where)
							.append('<hr>' +
									'<div id=\'dop\'><div class=\'row\'>Price: ' +
									'<select name=dop[price][type][0] id=sss'+row+' >' +
									'</select>' +
									'<input name=dop[price][price] type=text size=3 />' +
									'<div class="ui-icon ui-icon-plus" style="float:left" width=16 height=16 num="1" onClick="addRowlist(\'dop\');">+</div><div class=rowT></div>' +
									'</div>' +
									'</div>' +
									'<hr>');
							for(row2 in data[row])
							{
								$('#sss'+row,where)
								.append('<option value='+row2+' >'+
											data[row][row2]+
										'</option>');
							}
						}
					}
			/*	break;
				case '2':
					for(row in data)
					{
						
						if(data[row].constructor!=Object)
						{
							$(where).append(data[row]+': <input type=text size=3><br />');
						}
						else
						{
							$(where).append('<hr>Price: <select id=sss'+row+'></select><hr>');
							for(row2 in data[row])
							{
								$('#sss'+row,where).append('<option value='+row2+' >'+data[row][row2]+'</option>');
							}
						}
					}
				break;
				case '3':
					for(row in data)
					{
						
						if(data[row].constructor!=Object)
						{
							$(where).append(data[row]+': <input type=text size=3><br />');
						}
						else
						{
							$(where).append('<hr>Price: <select id=sss'+row+'></select><hr>');
							for(row2 in data[row])
							{
								$('#sss'+row,where).append('<option value='+row2+' >'+data[row][row2]+'</option>');
							}
						}
					}
				break;
			}*/
		}
	});
}
$(function()
{
		$('.showAllTables').click(function(){
			$.ajax({
				url: '/admin/showAllTables/'+$('#service').attr('type'),
				type:'post',
				success:function(data)
				{
					data=eval('('+data+')');
					tables=[];
					$('#tableList').empty();
					//console.log(data);
					for(row in data)
					{
						
						$('#tableList').append('<tr >'+
						'<td width="2%"> &nbsp;</td>'+
						'<td><h2>'+data[row]['name']+'</h2></td>'+
						'<td width="2%"> &nbsp;</td>'+
					'</tr>'+
					'<tr >'+
						'<td id=row'+row+'></td>'+
					'</tr>');
					for(line in data[row]['tables'])
					{
						$('#row'+row,'#tableList').append('<table><tr><td width="2%"> &nbsp;</td>'+
						'<td>'+
						'	<div id="pager'+data[row]['tables'][line]['id']+'"></div>'+
						'	<table id="table'+data[row]['tables'][line]['id']+'"></table>'+
						'	<script>tables.push('+data[row]['tables'][line]['id']+'); createTable("'+data[row]['tables'][line]['id']+'",$(".goMonth:eq(0)").attr("year"),$(".goMonth:eq(0)").attr("month"));</script>'+
						'</td>'+
						'<td width="2%"> &nbsp;</td></tr></table>');
					}
					
					}
				}
			});
		});
        //create new table
        $('.mWindowTest').mwindow({
                        trigger:'addTable',
                        context:ent+':<br/>' +
                        		'<input type=text name="name" ><br/> ' +
                        		edt+': ' +
                        		'<input type=text name="desc"><br/> ' +
                        		'<div id=tableoptions></div>' +
                        		struct+': <BR/>' +
                        		'<input type="hidden" value=1 id=numRows name=numRows>',
                        url:'/admin/addTableInService/'+$('#service').attr('service'),
                        submit:true,
                        name:new_table,
                        width:220,
                        height:150,
                        left:500,
                        top:200,
                        success:function(e){
                                $('#tableList').append(e);
                        }
                });
        //append row list to modal window
        //loadtableoptions('#tableoptions');
        $.ajax({
                url: '/admin/getRowList',
                type:'post',
                success:function(data)
                {
                        ////console.log(data);
                        list=data;
                        $('#mWFormId','.mWindowTest').append(list);

                }
        });
        // go to next month
        $('.goMonth').click(function()
        {
                $('.goMonth').each(function(){
                        if($(this).hasClass('goMonthChecked'))$(this).removeClass('goMonthChecked');
                });
                $(this).addClass('goMonthChecked');
                for(var i=0;i<tables.length;i++)
                {
                        createTable(tables[i],$(this).attr('year'),$(this).attr('month'));
                }
        });
        // modal window to edit the price

       $('.editPrice').mwindow({

                trigger:'class',
                context:'<table><tr><td><div class="navLeft">Cena</div></td><td><div class="navRight">Skidka</div></td></tr></table><input type="hidden" id="hiddenf1" name="idTable" value=""><input type="hidden" name="Skidka" id="skidka" value=0><table id="addPriceTable"></table><table><tr><td>Dates</td><td><input type=text class="date" id=dates name=dates><input type=button value=".." class="Calendar"></td></tr></table>',
                url:'/admin/addPrices/',
                submit:true,
                width:400,
                name:'Ввод данных',
                success:function(e)
                        {
                                $('#table'+$('#hiddenf1').val()).trigger('reloadGrid');
                            	$('.date').val('')
		                        //rows2($('#hiddenf1').attr('idTable'));
                            	$('#addPriceTable > *').find('input').each(function(){$(this).val('')});
		                        $('.editPrice').toggle();
                        }
        });
        $('.navLeft').click(function(){
        	$('#skidka').val('0');
        	$(this).addClass('goMonthChecked');
        	$('.navRight').removeClass('goMonthChecked');
        });
         $('.navRight').click(function(){
        	$('#skidka').val('1');
        	$(this).addClass('goMonthChecked');
        	$('.navLeft').removeClass('goMonthChecked');
        });
        // modal window whith calendar
        $('#Calendar').mcalendar({
                trigger:'Calendar',
                onSubmit:function(data)
                {
                	
                        $('#dates').val(data);
                }
        });
        // event to add new row in addTable
        $('.addNewRow').click(function(){
                addRowlist();
        });
        // show modal window addTable if service dont have tables
        if(tables.length==0)
        {
                $('.mWindowTest').toggle();
        }
        // set this month is checked
        $('.goMonth:eq(0)').addClass('goMonthChecked');
        //delete data by month
        $('.mWindowTestDeleteByMonth').mwindow({
                trigger:'deleteTableDataByMonth',
                context:'<input type="hidden" id="hiddenf3" name="idTable" value="">'+delete_conf+'<br/>',
                url:'/admin/deleteTableDataByMonth/'+$('#service').attr('service')+'/'+$('.goMonthChecked').attr('month')+'/'+$('.goMonthChecked').attr('year'),
                submit:true,
                width:220,
                height:150,
                success:function(e){
                        $('#table'+$('#hiddenf3').val()).trigger('reloadGrid');
                }
        });
        //модальное окно для клонирования таблицы
        $('.mWindowTestClone').mwindow({

                        trigger:'cloneTable',
                        context:'<input type="hidden" id="hiddenct" name="idTable" value="">'+enct+':<br/><input type=text name="name" ><br/> Введите описание таблицы <input type=text name="desc"><br/>',
                        url:'/admin/cloneTableInService/'+$('#service').attr('service'),
                        submit:true,
                        width:220,
                        height:150,
                        success:function(e){
                                $('#tableList').append(e);
                        }
                });
        $('.mWindowTestDelete').mwindow({
                trigger:'deleteTableData',
                context:'<input type="hidden" id="hiddenf2" name="idTable" value="" />'+delete_conf+'<br/>',
                url:'/admin/deleteTableData/'+$('#service').attr('service'),
                submit:true,
                width:220,
                height:150,
                success:function(e){
                        $('#table'+$('#hiddenf2').val()).trigger('reloadGrid');
                        //console.log('#table'+$('#hiddenf2').val()+" "+$('#service').attr('service'));
                }
        });

        $('.mWindowTestDeleteTable').mwindow({
                trigger:'deleteTable',
                context:'<input type="hidden" id="hiddenf4" name="idTable" value="" />'+delete_conf+'<br/>',
                url:'/admin/deleteTable/'+$('#service').attr('service'),
                submit:true,
                width:220,
                height:150,
                success:function(e){
                        $(window.location.reload());
                        //console.log('#table'+$('#hiddenf4').val()+" "+$('#service').attr('service'));
                }
        });

        $('.mWindowTestDeleteAllTables').mwindow({
                trigger:'deleteTables',
                context:'<input type="hidden" id="hiddenf5" name="idTable" value="" />'+delete_conf+'<br/>',
                url:'/admin/deleteTables/'+$('#service').attr('service'),
                submit:true,
                width:220,
                height:150,
                success:function(e){
                        $(window.location.reload());
                        //console.log('#table'+$('#hiddenf5').val()+" "+$('#service').attr('service'));
                }
        });
       
	    $(document).keydown(function(e)
	    {
	        if (e.keyCode == ctrlKey) ctrlDown = true;
	    }).keyup(function(e)
	    {
	        if (e.keyCode == ctrlKey) ctrlDown = false;
	    });
		
	    $('.date').keydown(function(e)
	    	{
	    		if (ctrlDown && (e.keyCode == vKey))
		       	 	{
		       	 		ctrlV=true;
		       	 	}
	   		}).keyup(function(e)
	    	{
	    		////console.log($(this).val());
			    if(ctrlV)
		   			{//2011-12-13,2011-12-12
		   				////console.log($(this).val());
		   				//var reg=/^\d{4}\-\d{1,2}\-\d{1,2}[,\d{4}\-\d{1,2}\-\d{1,2}]?$/;
		   				////console.log(reg.test($(this).val()));
		   				//04.01.2011 - 12.03.2011
		   				var reg1=/\d{4}\-\d{1,2}\-\d{1,2}/;
		   				var reg2=/\d{1,2}\,\d{1,2}/;
		   				var reg3=/\d{1,2}\.\d{1,2}/;
		   				var reg4=/\d{1,2}\.\d{1,2}\.\d{4}\s?\-\s?\d{1,2}\.\d{1,2}\.\d{4}/;
		   				//16.09
		   				//01.06;1,09;13,12
		   				var arr=$(this).val().split(';');
	   					var i=0;
	   					var num=arr.length;
	   					var str=[];
	   					for (var val in arr)
		   				{
		   					if(reg1.test(arr[val]))
		   					{
		   						//console.log('reg1');
		   						str.push(arr[val]);
		   					}
		   					else
		   					{
		   						if(reg2.test(arr[val]))
		   						{
		   							//console.log('reg2');
		   							var date=arr[val].split(',');
		   							dateA=new Date(new Date().getFullYear(),date[1],date[0]);
		   							if(dateA<new Date())
		   							{
		   								str.push((new Date().getFullYear()+1)+"-"+$.trim(date[1])+"-"+$.trim(date[0]));
		   							}
		   							else
		   							{
		   								str.push((new Date().getFullYear())+"-"+$.trim(date[1])+"-"+$.trim(date[0]));
		   							}
		   							
		   						}
		   						else
		   						{
		   							if(reg3.test(arr[val]))
			   						{
			   							if(reg4.test(arr[val]))
				   						{
				   							//console.log('reg4');
				   							var dates=arr[val].split('-');
				   							var d1=dates[0].split('.');
				   							var d2=dates[1].split('.');
				   							
				   							var dateB=new Date(d2[2],d2[1]-1,d2[0]);
				   							y=(d1[2]);
				   							m=(d1[1])-1;
				   							d=(d1[0]);
				   							
				   							y2=(d2[2]);
				   							m2=(d2[1]);
				   							d2=(d2[0]);
				   							
				   							//console.log(y+'Y '+m+'M '+d+'D  d='+d);
				   							//console.log(y2+'Y '+m2+'M '+d2+'D  ');
				   							var dateA=new Date(y,(m),d);
				   							//console.log(dateA.getFullYear()+'-'+(dateA.getMonth()+1)+'-'+dateA.getDate()+'  d='+d)
				   							//console.log(dateB.getFullYear()+'-'+(dateB.getMonth()+1)+'-'+dateB.getDate()+'  dB')
				   							while(dateA<=dateB)
				   							{
				   								str.push(dateA.getFullYear()+'-'+(dateA.getMonth()+1)+'-'+dateA.getDate());
				   								//console.log(dateA.getFullYear()+'-'+(dateA.getMonth()+1)+'-'+dateA.getDate()+'  d='+d)
				   								d++;
				   								if(((m+1)!=2?(((m+1)%2)^((m+1)>7))+30:(!(y%400)||!(y%4)&&(y%25)?29:28))<d)
				   								{
				   									d=1;
				   									m++;
				   									if(m>11)
				   									{
				   										m=0;
				   										y++;
				   									}
				   								}
				   								dateA=new Date(y,(m),d);
				   								//console.log(dateA.getDate());
				   							}
				   							
				   						}
				   						else
				   						{
					   						//console.log('reg3');
				   							var date=arr[val].split('.');
				   							dateA=new Date(new Date().getFullYear(),date[1],date[0]);
				   							if(dateA<new Date())
				   							{
				   								str.push((new Date().getFullYear()+1)+"-"+$.trim(date[1])+"-"+$.trim(date[0]));
				   							}
				   							else
				   							{
				   								str.push((new Date().getFullYear())+"-"+$.trim(date[1])+"-"+$.trim(date[0]));
				   							}
					   					}
			   							
				   					}
				   				
		   						}
		   					}
		   				}
		   				//console.log(str)
		   				$(this).val(str.join(';'));
		   			}
		   		ctrlV=false;
	    	});
	   
});
 		var ctrlDown = false;
	    var ctrlKey = 17, vKey = 86, cKey = 67;
		var ctrlV=false;
	function rows2(id)
        {
        	mRows='';
        	i=0;
        	//console.log($('#table'+id+'').find('tr.jqgrow'));
        	//console.log('#table'+id+'.jqrow');
        	$('#table'+id+'').find('tr.jqgrow').each(function()
        		{
        			mRows+='<tr><td>'+$(this).find('td').eq(1).html()+'</td><td><input type="text" class="price" name="r['+$(this).find('td').eq(0).html()+']"></td></tr>'
        		}
        	);
        	$('#addPriceTable').html(mRows);
        	$(".price").keydown(function(e)
	    	{
	       	 	if (ctrlDown && (e.keyCode == vKey))
	       	 	{
	       	 		ctrlV=true;
	       	 	}
	   		}).keyup(function(e){
	   			if(ctrlV)
	   			{
	   				var arr=$(this).val().split('\t');
	   				var i=0;
	   				var num=arr.length;
	   				////console.log(arr);
	   				if(num>1)
	   				{
		   				$('.price').each(function()
		   				{
		   					if(i<=num)
		   					{
		   						$(this).val(arr[i]);
		   					}
		   					i++;
		   				});
	   				}
	   				ctrlV=false;
	   			}
	   		});
        }
   function contextMenuWork(action, el, pos)
   {
		switch (action)
		{
			case"delete":
				$('#hiddenf2').val($(el).attr('idtable'));
				$('.mWindowTestDelete')
				.css('left',($(window).width()/2+$(window).scrollLeft()-200)+'px')
				.css('top',($(window).height()/2+$(window).scrollTop()-200)+'px')
				.toggle();
			break;
			case"deletetable":
				$('#hiddenf4').val($(el).attr('idtable'));
				$('.mWindowTestDeleteTable')
				.css('left',($(window).width()/2+$(window).scrollLeft()-200)+'px')
				.css('top',($(window).height()/2+$(window).scrollTop()-200)+'px')
				.toggle();
			break;
			case"deletebymonth":
				$('#hiddenf3').val($(el).attr('idtable'));
				$('.mWindowTestDeleteByMonth')
				.css('left',($(window).width()/2+$(window).scrollLeft()-200)+'px')
				.css('top',($(window).height()/2+$(window).scrollTop()-200)+'px')
				.toggle();
			break;
			case"addprice":
				$('#hiddenf1').val($(el).attr('idTable'));
				$('.date').val('')
				rows2($(el).attr('idTable'));
				$('#Calendar')
				.css('left',($(window).width()/2+$(window).scrollLeft()-250)+'px')
				.css('top',($(window).height()/2+$(window).scrollTop()-300)+'px');
				$('.editPrice')
				.css('left',($(window).width()/2+$(window).scrollLeft()-200)+'px')
				.css('top',($(window).height()/2+$(window).scrollTop()-200)+'px')
				.toggle();
			break;
			case"clone":
				$('#hiddenct').val($(el).attr('idTable'));
				$('.mWindowTestClone')
				.css('left',($(window).width()/2+$(window).scrollLeft()-200)+'px')
				.css('top',($(window).height()/2+$(window).scrollTop()-200)+'px')
				.toggle();
			break;
		}
  }

